package com.itheima;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/register")
public class ServletRegister extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //第一句 就是设置编码
       // req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //封装用户对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        /*String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);*/

        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User u = mapper.selectByUsername(username);
        PrintWriter writer = resp.getWriter();
        if ( u == null){
            mapper.add(user);
            sqlSession.commit();
            sqlSession.close();
            writer.print("<!DOCTYPE html>\n" +
                    "<html lang=\"en\">\n" +
                    "<head>\n" +
                    "    <meta charset=\"UTF-8\">\n" +
                    "    <title>Title</title>\n" +
                    "</head>\n" +
                    "<body>\n" +
                    "<span id=\"time\">10</span>\n" +
                    "<script>\n" +
                    "    var sec = 10;\n" +
                    "    setInterval(function (){\n" +
                    "        if (sec>0){\n" +
                    "            sec--;\n" +
                    "            document.getElementById('time').innerHTML =\"倒计时\"+ sec+\"秒后跳转登录界面....\";\n" +
                    "        }else{\n" +
                    "            window.location.href = \"/login.html\";\n" +
                    "        }\n" +
                    "\n" +
                    "    },1000);\n" +
                    "</script>\n" +
                    "</body>\n" +
                    "</html>");
        }else{
            resp.getWriter().write("用户已存在");
        }


    }

}